
/*
 * Copyright (c) 2005, 2014 vacoor
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 */
Dnd = function () {
    var me = this;

    me.files = [];
    me.opts = {
    };

    me.defaultOptions = {
        dragEnter: function (e) {},
        dragOver: function (e) {
            me.className = "drag-zone-over";
        },
        dragLeave: function (e) {
            e.currentTarget == me && (e.target.className = "");
        },
        drop: function (e) {
            e.currentTarget == me && (e.target.className = "");
        }
    };

    me.applyIf(me.opts, me.defaultOptions);
};

Dnd.prototype = {
    applyIf: function (object, config) {
        var property;

        if (object) {
            for (property in config) {
                if (object[property] === undefined) {
                    object[property] = config[property];
                }
            }
        }

        return object;
    },

    /* ***************************
     *          DnD
     * ***************************/

    /* 拖拽释放 */
    onDrop: function (e) {
        var me = this;
        me.opts.drop(e);

        if (e.dataTransfer) {
            // chrome support drag-n-drop for folder
            if (e.dataTransfer.items && typeof e.dataTransfer.items[0].webkitGetAsEntry === 'function') {
                var items = e.dataTransfer.items, entry;
                for (var i = 0; i < items.length; i++) {
                    entry = items[i].webkitGetAsEntry();
                    entry && me.traverseFileTree(entry, "", e.currentTarget);   // 遍历目录
                }
            } else {
                // other unsupport folder
                var files = e.dataTransfer.files, file;
                for (var i = 0; i < files.length; i++) {
                    file = files[i];
                    // beforeLoad??
                    me.isFolder(file, function (folder) {
                        if (folder) {
                            // TODO ...
                            throw new Error("current browser is not support drag folders");
                            // 这样写是为了能在 beforeEach 中获取 dropArea
                        } else {
                            file.dropArea = e.currentTarget;
                            file.index = 123;   // TODO
                            file.fullPath = file.name;
                            file.parentPath = "";

                            if (0 != me.onFileSelected(file)) {
                                me.files.push(file);    // TODO
                            }
                        }
                    });
                }

                if (!me.files || me.files.length < 1) {
                    // error
                }

                // me.afterLoad();
                // me.upload();
            }
        } else {
            // Unsupported
        }
        return e.preventDefault(), false;
    },

    traverseFileTree: function (entry/*file entry*/, path, dropArea) {
        var me = this, path = path || "";

        if (entry.isFile) {
            // 本地系统 file() / readEntiries()  读取不到内容, 必须在 Server 运行
            entry.file(function (file) {
                file.dropArea = dropArea;
                file.fullPath = entry.fullPath || (path + file.name);
                file.parentPath = path;
                0 == file.fullPath.indexOf('/') && (file.fullPath = file.fullPath.substring(1));

                if (0 != me.onFileSelected(file)) {
                    console.log(file);
                    me.files.push(file);
                }
            });
        } else if (entry.isDirectory) {
            /* 遍历目录 */
            entry.createReader().readEntries(function (entries) {
                for (var i = 0; i < entries.length; i++) {
                    me.traverseFileTree(entries[i], path + entry.name + "/", dropArea);
                }
            });
        }
    },

    onDragEnter: function (e) {
        var me = this;
        e.preventDefault();
        me.opts.dragEnter && me.opts.dragEnter(e);
    },

    onDragOver: function (e) {
        var me = this;
        e.preventDefault();
        me.opts.dragOver && me.opts.dragOver(e);
    },

    onDragLeave: function (e) {
        var me = this;
        me.opts.dragLeave && me.opts.dragLeave(e);
        e.stopPropagation();
    },

    /* **********************
     *
     * **********************/

    isFolder: function (file, callback) {
        var reader;
        if (!file.type) {
            try {
                reader = new FileReader();
                reader.onload = function () {
                    callback(false)
                };
                reader.onerror = function () {
                    callback(true)
                };
                reader.readAsDataURL(file);
            } catch (e) {
                callback(true);
            }
        } else {
            callback(false);
        }
    },

    /* 返回 0 "", false 终止 */
    onFileSelected: function (file) {
        var div = document.createElement("div");
        div.innerHTML = file.name + " " + file.size + " " + file.type + " " + file.fullPath + " " + file.parentPath, document.body.appendChild(div);
        return true;
    },

    bindDropArea: function (e) {
        if (e) {
            var me = this;
            e.addEventListener('drop', function () { me.onDrop.apply(me, arguments) }, false);
            e.addEventListener('dragenter', function () { me.onDragEnter.apply(me, arguments) }, false);
            e.addEventListener('dragover', function () { me.onDragOver.apply(me, arguments) }, false);
            e.addEventListener('dragleave', function () { me.onDragLeave.apply(me, arguments) }, false);
        }
    }
};

var dnd = new Dnd();
dnd.bindDropArea(document.getElementById("drag-zone"));

 